package com.itboye.mengwu.app.ui.mymeng;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.buy.ui.DaiFuKuanDetail;
import com.itboye.mengwu.buy.ui.PayTypeActivity;
import com.itboye.mengwu.data.model.OrderBean;
import com.itboye.mengwu.data.model.OrderQueryModel;
import com.itboye.mengwu.data.model.OrderQueryModel.OrderList;
import com.itboye.mengwu.data.presenter.OrderPresenter;
import com.itboye.mengwu.widget.CustomDialog;
import com.itboye.mengwu.widget.XListView;
import com.itboye.mengwu.widget.XListView.IXListViewListener;

public class FragmentDaiFuKuan extends BaseFragment implements Observer,
		IXListViewListener {
	XListView wait_pay_list;
	OrderPresenter orderPresenter;
	private ArrayList<OrderQueryModel.OrderList> model = new ArrayList<OrderQueryModel.OrderList>();
	RelativeLayout re_nodata;
	OrderBean model2 = new OrderBean();
	int pageNo;
	MyAdapter adapter = null;

	// List<OrderBean> beans=new ArrayL;
	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.list_wait_pay;
	}

	@Override
	public void onMyActivityCreated() {
		System.out.println("qita");
		IntentFilter filter=new IntentFilter("refresh");
		getActivity().registerReceiver(receiver, filter);
		adapter = new MyAdapter(getActivity(), R.layout.item_wait_pay);
		wait_pay_list.setAdapter(adapter);
		// showProgressDialog("数据加载中，请稍后", true);
		orderPresenter = new OrderPresenter(this);
		wait_pay_list.setPullLoadEnable(true);
		wait_pay_list.setXListViewListener(this);
		wait_pay_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), DaiFuKuanDetail.class);
				intent.putExtra("type", "1");
				intent.putExtra("model", model.get(position - 1));
				intent.putExtra("id", model.get(position - 1).getId());
				startActivity(intent);
			}
		});
		// castlove_list_2.setOnItemClickListener(this);
	}
	
	BroadcastReceiver  receiver=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			refresh();
		}
	};

	public void refresh() {
		pageNo = 1;
		model2.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
				+ "");
		model2.setStatus(1 + "");
		model2.setPageNo(pageNo + "");

		orderPresenter.getInfo(model2);
	}

	public void loadMore() {
		pageNo++;
		model2.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
				+ "");
		model2.setStatus(1 + "");
		model2.setPageNo(pageNo + "");
		orderPresenter.getInfo(model2);
	}

	private CustomDialog dialog;

	class MyAdapter extends BaseAdapter {
		Context context;
		int resID;

		public MyAdapter(Context context, int resID) {
			this.context = context;
			this.resID = resID;
		}

		@Override
		public int getCount() {
			return model.size();
		}

		@Override
		public Object getItem(int position) {
			return model.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder view;
			int count = 0;
			if (convertView == null) {
				view = new ViewHolder();
				convertView = CreateView();
				view.cancle_pay = (Button) convertView
						.findViewById(R.id.cancle_pay);
				view.go_pay = (Button) convertView.findViewById(R.id.go_pay);
				view.total_num_tv = (TextView) convertView
						.findViewById(R.id.total_num_tv);
				view.total_price = (TextView) convertView
						.findViewById(R.id.total_price);
				view.wait_pay_iv = (ImageView) convertView
						.findViewById(R.id.wait_pay_iv);
				view.txt_yunfei = (TextView) convertView
						.findViewById(R.id.yunfei);
				view.txt_oldPrice = (TextView) convertView
						.findViewById(R.id.goods_old_price);
				view.goodsgroup = (LinearLayout) convertView
						.findViewById(R.id.goodsgroup);
				convertView.setTag(view);
			} else {
				view = (ViewHolder) convertView.getTag();
			}
			view.cancle_pay.setText("取消订单");
			view.cancle_pay.setTag(model.get(position).getOrderCode());
			view.cancle_pay.setTag(R.id.tag_first, position);
			view.go_pay.setTag(model.get(position).getId());
			view.go_pay.setTag(R.id.tag_first, position);
			view.cancle_pay.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View v) {
					// TODO Auto-generated method stub
					CustomDialog.Builder customBuilder = new CustomDialog.Builder(
							getActivity());
					customBuilder
							.setTitle("取消订单")
							.setMessage("是否取消该订单")
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.dismiss();
										}
									})
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											showProgressDialog("数据请求中，请稍后",
													true);
											OrderBean model = new OrderBean();
											model.setUid(SPUtils.get(
													getActivity(), null,
													SpPublicParams.UID, "")
													+ "");
											System.out.println(v.getTag()
													+ "订单Code");
											model.setCode(v.getTag() + "");
											orderPresenter.delete(model);

											dialog.dismiss();
										}
									});
					dialog = customBuilder.create();
					dialog.show();
				}
			});
			view.go_pay.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(),
							PayTypeActivity.class);
					OrderBean bean = new OrderBean();
					bean.setTotalPrice(Double.parseDouble(model.get(position).getPrice())-Double.parseDouble(model.get(position).getDiscountMoney())-Double.parseDouble(model.get(position).getPayBalance())+"");
					bean.setCode(model.get(position).getOrderCode());
					bean.setDesc(model.get(position).getOrderCode());
					intent.putExtra("model", bean);
					startActivity(intent);
				}
			});
			view.goodsgroup.removeAllViews();
			for (int i = 0; i < model.get(position).getItems().size(); i++) {

				View childView = LayoutInflater.from(getActivity()).inflate(
						R.layout.goods_item, null);
				((TextView) childView.findViewById(R.id.dangge_shuliang))
						.setText("x"
								+ model.get(position).getItems().get(i)
										.getCount());
				((TextView) childView.findViewById(R.id.goods_old_price))
						.setText("￥"
								+ model.get(position).getItems().get(i)
										.getOriPrice());
				((TextView) childView.findViewById(R.id.goods_old_price))
						.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
				XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
						+ model.get(position).getItems().get(i).getImgUrl(),
						((ImageView) childView.findViewById(R.id.wait_pay_iv)));
				((TextView) childView.findViewById(R.id.goods_price))
						.setText("￥"
								+ model.get(position).getItems().get(i)
										.getPrice());
				((TextView) childView.findViewById(R.id.goodsname_tv))
						.setText(model.get(position).getItems().get(i)
								.getName());
				((TextView) childView.findViewById(R.id.buy_num)).setText(model
						.get(position).getItems().get(i).getSkuDesc());
				count += Integer.parseInt(model.get(position).getItems().get(i)
						.getCount());
				view.goodsgroup.addView(childView);
			}

			view.total_num_tv.setText("共"
					+ count + "件商品");

			view.total_price
					.setText("￥"
							+ (Double.parseDouble(model.get(position)
									.getPrice())
									- Double.parseDouble(model.get(position)
											.getDiscountMoney()) + Double
										.parseDouble(model.get(position)
												.getPostPrice())) + "");

			view.txt_yunfei.setText("(含运费￥"
					+ model.get(position).getPostPrice() + ")  优惠 ￥"
					+ model.get(position).getDiscountMoney());
			return convertView;
		}

		private View CreateView() {
			View v = null;
			LayoutInflater inflater = LayoutInflater.from(context);
			v = inflater.inflate(R.layout.item_wait_pay, null);

			return v;
		}

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		refresh();
	}

	class ViewHolder {
		private Button cancle_pay, go_pay;
		TextView total_num_tv, txt_oldPrice, txt_yunfei, total_price;
		ImageView wait_pay_iv;
		LinearLayout goodsgroup;
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == OrderPresenter.OrderQuerySuccess) {
				if (pageNo == 1) {
					model.clear();
				}
				model.addAll(((OrderQueryModel) entity.getData()).getList());
				adapter.notifyDataSetChanged();
				if (model.size() <= 0) {
					re_nodata.setVisibility(View.VISIBLE);
					wait_pay_list.setVisibility(View.GONE);
				} else {
					re_nodata.setVisibility(View.GONE);
					wait_pay_list.setVisibility(View.VISIBLE);
				}
			} else if (entity.getEventType() == OrderPresenter.OrderDeleteSuccess) {
				ByAlert.alert(entity.getData() + "");
				refresh();
			}
		}
		stopLoad();
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		refresh();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		loadMore();
	}

	public void stopLoad() {
		wait_pay_list.stopLoadMore();
		wait_pay_list.stopRefresh();
	}

}
